package com.vehicle.repair.controller;

import com.vehicle.repair.model.WorkLog;
import com.vehicle.repair.service.WorkLogService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/worklogs")
public class WorkLogController {
    private final WorkLogService workLogService;

    public WorkLogController(WorkLogService workLogService) {
        this.workLogService = workLogService;
    }

    @PostMapping
    public ResponseEntity<WorkLog> addWorkLog(@RequestBody WorkLog workLog,
                                           @RequestParam Integer orderId,
                                           @RequestParam Integer repairerId) {
        try {
            WorkLog savedLog = workLogService.addWorkLog(workLog, orderId, repairerId);
            return ResponseEntity.ok(savedLog);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<WorkLog> getWorkLogById(@PathVariable Integer id) {
        Optional<WorkLog> log = workLogService.getWorkLogById(id);
        return log.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @GetMapping("/order/{orderId}")
    public ResponseEntity<List<WorkLog>> getWorkLogsByOrder(@PathVariable Integer orderId) {
        try {
            List<WorkLog> logs = workLogService.getWorkLogsByOrder(orderId);
            return ResponseEntity.ok(logs);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/repairer/{repairerId}")
    public ResponseEntity<List<WorkLog> getWorkLogsByRepairer(@PathVariable Integer repairerId) {
        try {
            List<WorkLog> logs = workLogService.getWorkLogsByRepairer(repairerId);
            return ResponseEntity.ok(logs);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteWorkLog(@PathVariable Integer id) {
        workLogService.deleteWorkLog(id);
        return ResponseEntity.noContent().build();
    }
}
